<template>
  <el-dialog width="70%"
    :title="!dataForm.id ? '新增合同' : '修改合同'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="110px" style="text-align: left;">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="dataForm.contractName" placeholder="合同名称"></el-input>
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="dataForm.contractNo" placeholder="合同编号" disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="合同金额" prop="contractMoney" >
            <el-input v-model="dataForm.contractMoney" placeholder="合同金额" type="number" :precision="2" step="0.01" autocomplete="true"
                      @change="dataForm.contractMoney = parseFloat(dataForm.contractMoney).toFixed(2)"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同类型:" prop="contractType">
            <el-radio-group v-model="dataForm.contractType">
              <el-radio :label="0">合同委托</el-radio>
              <el-radio :label="1">一般委托</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="委托单位" prop="contractAuthorize">
            <el-input v-model="dataForm.contractAuthorize" placeholder="委托单位"></el-input>
          </el-form-item>
          <el-form-item label="联系人姓名" prop="userName">
            <el-input v-model="dataForm.userName" placeholder="联系人名称"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话" prop="userPhone">
            <el-input v-model="dataForm.userPhone" placeholder="联系人电话" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12">
          <el-form-item label="业务负责人" prop="contractBusiness">
            <el-autocomplete v-model="dataForm.contractBusiness" :fetch-suggestions="queryBusinessSearch" @select="((item)=>{handleBussinessSelect(item)})"
                             required="true" style="width: 100%" placeholder="业务负责人">
              <template slot-scope="{ item }">
                <div class="name">{{ item.username }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="业务来源" prop="contractOrigin">
            <el-input v-model="dataForm.contractOrigin" placeholder="业务来源" ></el-input>
          </el-form-item>
          <el-form-item label="订做合同时间" prop="contractFormlTime">
            <el-date-picker v-model="dataForm.contractFormlTime" type="date" value-format="yyyy-MM-dd" placeholder="订做合同时间" style="width: 150px;" ></el-date-picker>
          </el-form-item>
          <el-form-item label="是否签订合同:" prop="sign">
            <el-radio-group v-model="dataForm.sign" @change="dataForm.contractAddTime = null">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="签订合同时间" prop="contractAddTime" >
            <el-date-picker v-model="dataForm.contractAddTime" type="date" value-format="yyyy-MM-dd" placeholder="合同签订时间" style="width: 150px;" :disabled="dataForm.sign !== 1"></el-date-picker>
          </el-form-item>


          <el-form-item label="项目附件" prop="attachFilename">
            <el-upload :action="upContractUrl"
                       :data="{'contractNo': dataForm.contractNo}"
                       :limit="1"
                       name="file"
                       ref="attachUpload"
                       accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlxs,image/*"
                       :headers="tokenHeaders"
                       :before-upload="handleBeforeUpload"
                       :on-success="handleAttachSuccess"
                       :on-error="handleError">
              <el-button size="small" plain>选择文件</el-button>
              <div slot="tip" style="color: dodgerblue" v-if="!stringIsNull(dataForm.attachFilename)">
                已上传文件:<el-tag closable @close="dataForm.attachFilename = ''">{{dataForm.attachFilename}}</el-tag>
              </div>
              <div slot="tip" class="el-upload__tip">只能上传pdf,word,图片文件，且不超过10M</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="商务合同" prop="contractFilename">
            <el-upload :action="upContractUrl"
                       :data="{'contractNo': dataForm.contractNo}"
                       :limit="1"
                       name="file"
                       ref="contractUpload"
                       accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlxs,image/*"
                       :headers="tokenHeaders"
                       :before-upload="handleBeforeUpload"
                       :on-success="handleContractSuccess"
                       :on-error="handleError">
              <el-button size="small" plain>选择文件</el-button>
              <div slot="tip" style="color: dodgerblue" v-if="!stringIsNull(dataForm.contractFilename)">
                已上传文件:<el-tag closable @close="dataForm.contractFilename = ''">{{dataForm.contractFilename}}</el-tag>
              </div>
              <div slot="tip" class="el-upload__tip">只能上传pdf,word,图片文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'

  import {isMobile} from '../../../utils/validate'
  import {isPhone} from '../../../utils/validate'
  import {stringIsNull} from '../../../utils'

  export default {
    data () {
      let checkPhone = (rule, value, callback) => {
        if (!value) {
          callback()
        } else {
          if (isMobile(value) || isPhone(value)) {
            callback()
          } else {
            return callback(new Error('请输入正确的手机号'))
          }
        }
      }
      return {
        visible: false,
        dataForm: {
          id: 0,
          contractNo: '',
          contractAddTime: '',
          contractFormlTime: '',
          contractCreateTime: '',
          contractAuthorize: '',
          contractName: '',
          contractType: '',
          contractNote: '',
          contractBusiness: '',
          contractBusinessId: '',
          contractOrigin: '',
          contractStage: '',
          contractMoney: '',
          projectType: '',
          sign: 0,
          attachFilename: '',
          contractFilename: '',
          userPhone: '',
          userName: '',
          projectTypeIdList: []
        },
        businessList: [], // 业务员列表
        projectTypeList: [], // 项目类型列表
        upContractUrl: window.SITE_CONFIG['baseUrl'] + '/project/contract/upContractFile/',  // 合同上传地址
        tokenHeaders: { token: Vue.cookie.get('token') },  // token请求
        dataRule: {
          contractNo: [
            { required: true, message: '合同编号不能为空', trigger: 'blur' }
          ],
          sign: [
            { required: true, message: '是否签订合同签不能为空', trigger: 'blur' }
          ],
          contractAuthorize: [
            { required: true, message: '委托单位不能为空', trigger: 'blur' }
          ],
          contractName: [
            { required: true, message: '合同名称不能为空', trigger: 'blur' }
          ],
          contractType: [
            { required: true, message: '合同类型不能为空', trigger: 'blur' }
          ],
          contractBusiness: [
            { required: true, message: '业务负责人不能为空' }
          ],
          contractOrigin: [
            { required: true, message: '业务来源不能为空' }
          ],
          contractMoney: [
            { required: true, message: '合同金额不能为空', trigger: 'blur' }
          ],
          userPhone: [
            { required: false, message: '联系人电话不正确', trigger: 'blur', validator: checkPhone }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.getProjectTypeList().then(ptList => {
            this.projectTypeList = ptList
            this.getBusinessList().then(busList => {
              this.businessList = busList
              this.$refs['dataForm'].resetFields()
              if (this.dataForm.id) {
                this.$http({
                  url: this.$http.adornUrl(`/project/contract/info/${this.dataForm.id}`),
                  method: 'get',
                  params: this.$http.adornParams()
                }).then(({data}) => {
                  if (data && data.code === 0) {
                    this.dataForm.contractNo = data.projectContract.contractNo
                    this.dataForm.sign = data.projectContract.sign
                    this.dataForm.contractFormlTime = data.projectContract.contractFormlTime
                    this.dataForm.contractAddTime = data.projectContract.contractAddTime
                    this.dataForm.contractCreateTime = data.projectContract.contractCreateTime
                    this.dataForm.contractAuthorize = data.projectContract.contractAuthorize
                    this.dataForm.contractName = data.projectContract.contractName
                    this.dataForm.contractType = data.projectContract.contractType
                    this.dataForm.contractNote = data.projectContract.contractNote
                    this.dataForm.contractBusiness = data.projectContract.contractBusiness
                    this.dataForm.contractOrigin = data.projectContract.contractOrigin
                    this.dataForm.contractStage = data.projectContract.contractStage
                    this.dataForm.contractMoney = parseFloat(data.projectContract.contractMoney).toFixed(2)
                    this.dataForm.projectType = data.projectContract.projectType
                    this.dataForm.attachFilename = data.projectContract.attachFilename
                    this.dataForm.contractFilename = data.projectContract.contractFilename
                    this.dataForm.userPhone = data.projectContract.userPhone
                    this.dataForm.userName = data.projectContract.userName
                    this.dataForm.projectTypeIdList = []
                    for (let ptypeName of data.projectContract.projectType.split(',')) {
                      for (let ptype of ptList) {
                        if (ptype.name === ptypeName) this.dataForm.projectTypeIdList.push(ptype.id)
                      }
                    }
                  }
                })
              } else {
                this.dataForm.contractAddTime = ''
                this.dataForm.contractAuthorize = ''
                this.dataForm.contractName = ''
                this.dataForm.contractType = 0
                this.dataForm.contractNote = ''
                this.dataForm.contractBusiness = ''
                this.dataForm.contractOrigin = ''
                this.dataForm.contractStage = ''
                this.dataForm.contractMoney = 0
                this.dataForm.projectType = ''
                this.dataForm.attachFilename = ''
                this.dataForm.contractFilename = ''
                this.dataForm.userPhone = ''
                this.dataForm.userName = ''
                this.dataForm.projectTypeIdList = []
                this.dataForm.contractBusinessId = ''
                this.getMaxcontractNo()
              }
            })
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/project/contract/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'contractNo': this.dataForm.contractNo,
                'sign': this.dataForm.sign,
                'contractFormlTime': this.dataForm.contractFormlTime == null ? '' : this.dataForm.contractFormlTime,
                'contractAddTime': this.dataForm.contractAddTime == null ? '' : this.dataForm.contractAddTime,
                'contractCreateTime': this.dataForm.contractCreateTime,
                'contractAuthorize': this.dataForm.contractAuthorize,
                'contractName': this.dataForm.contractName,
                'contractType': this.dataForm.contractType,
                'contractNote': this.dataForm.contractNote,
                'contractFilename': this.dataForm.contractFilename,
                'attachFilename': this.dataForm.attachFilename,
                'contractBusiness': this.dataForm.contractBusiness,
                'contractOrigin': this.dataForm.contractOrigin,
                'contractStage': this.dataForm.contractStage,
                'contractMoney': this.dataForm.contractMoney,
                'projectType': this.dataForm.projectType,
                'filename': this.dataForm.filename,
                'userPhone': this.dataForm.userPhone,
                'userName': this.dataForm.userName
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 新增合同获取合同编号
      getMaxcontractNo () {
        this.$http({
          url: this.$http.adornUrl(`/project/contract/getMaxContractNo`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.contractNo = data.contractNo
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 获取项目类型列表
      getProjectTypeList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/set/projecttype/getProjectTypelist`),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.$message.error(data.msg)
              reject(data.msg)
            }
          })
        })
      },
      // 获取业务员列表
      getBusinessList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/project/contract/getBusinessList`),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.$message.error(data.msg)
              reject(data.msg)
            }
          })
        })
      },
      // 业务员查找项
      queryBusinessSearch (queryString, cb) {
        var list = this.businessList
        var results = queryString ? list.filter(this.businessFilter(queryString)) : list
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      businessFilter (queryString) {
        return (restaurant) => {
          return (restaurant.username.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      handleBussinessSelect (item, id) {
        this.dataForm.contractBusiness = item.username
      },
      // 上传文件之前的钩子
      handleBeforeUpload (file) {
        let size = file.size / 1024 / 1024 / 10
        if (size > 10) {
          this.$message({
            message: '文件必须小于10M',
            type: 'warning',
            duration: 1500
          })
        }
      },
      // 附件文件上传成功时的钩子
      handleAttachSuccess (res, file, fileList) {
        console.log(res.fileName)
        this.dataForm.attachFilename = res.fileName
        this.$message({
          message: '文件上传成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$refs.attachUpload.clearFiles()
          }
        })
      },
      // 合同文件上传成功时的钩子
      handleContractSuccess (res, file, fileList) {
        console.log(res.fileName)
        this.dataForm.contractFilename = res.fileName
        this.$message({
          message: '文件上传成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$refs.contractUpload.clearFiles()
          }
        })
      },
      // 文件上传失败时的钩子
      handleError (err, file, fileList) {
        this.$message.error('文件上传失败')
      }
    }
  }
</script>
